import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
import JSZip from 'jszip';

/**
 导出docx
 @param { String } tempDocxPath 模板文件路径
 @param { Object } data 文件中传入的数据
 @param { String } fileName 导出文件名称
 */
export const exportDocx = (tempDocxPath, data, fileName) => {
    // 读取并获得模板文件的二进制内容
    JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => {

        if (error) {
            throw error
        }
        const jsZip = new JSZip();
        data.forEach(item => {
            const zip = new PizZip(content)
            const doc = new docxtemplater().loadZip(zip).compile();
            doc.setData(item);
            doc.render()
            const generateWord = doc.getZip().generate({
                type: 'blob',
                mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            })
            jsZip.file(item.name + "_" + new Date().getTime() + "_" + fileName + ".docx", generateWord)
        })
        // 生成压缩包并下载
        jsZip.generateAsync({type: 'blob'})
            .then(function (content) {
                saveAs(content, fileName + ".zip");
            });
    })
}
